package com.zhu.storesmanager.network;

import com.zhu.storesmanager.R;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.SyncModel.ResultStatus;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.SalesData;
import com.zhu.storesmanager.views.SyncView;

import android.content.Context;
import android.database.Cursor;
import android.os.Handler;

/**
 * 促销员数据同步
 */
public class SyncData {

	//同步步骤
	private static final int SETUP_STARTSYNC = 1; //开始同步
	private static final int SETUP_GETMODELS = 2; //获取所有型号数据
	private static final int SETUP_GETPROJECTS = 3; //获取数据标签项目
	private static final int SETUP_GETREMINDS = 4; //获取提醒数据
	private static final int SETUP_PUTCHECKINFO = 5; //上报签入数据
	private static final int SETUP_PUTSALES= 6; //上报销量数据
	private static final int SETUP_PUTTASK= 7; //上报特殊任务
	private static final int SETUP_FINISHSYNC= 8; //上报同步结束

	private Context mContext; //上下文
	private Handler mHandler = null; //消息处理Handler
	private int mConnectStep = -1; //当前同步到第几阶段
	private int retryCount = 0; //重试次数
	private boolean isFirstSync = false;

	//同步结果数据
	private SyncModel.StartResult mStartResult = null; //开始同步
	private SyncModel.ProductResult mProductResult = null;//型号数据
	private SyncModel.PromoterSalesResult mPromoterSalesResult = null; //销量上报结果
	private SyncModel.ProjectResult mProjectResult = null; //拜访项目标签
	private SyncModel.ReminderResult mReminderResult = null; //提醒数据

	/**
	 * 构造函数
	 * @param context 上下文
	 * @param handler 消息处理Handler
	 */
	public SyncData(Context context, Handler handler){
		mContext = context;
		mHandler = handler;
	}

	/**
	 * 开始同步
	 */
	public void startSync(){
		mConnectStep = -1;
		retryCount = 0;
		resetData();
		isFirstSync = isFirstSync();
		requstStartSync();
	}

	 /**
     * 重试连接
     */
    private void retryConnect(){
    	switch(mConnectStep){
    		case SETUP_STARTSYNC:
    			requstStartSync();
    			break;
    		case SETUP_GETMODELS:
    			requstModels();
    			break;
    		case SETUP_GETPROJECTS:
    			requstProjects();
    			break;
    		case SETUP_GETREMINDS:
    			requstReminds();
    			break;
            case SETUP_PUTCHECKINFO:
            	putPromoterCheckInfo();
                break;
            case SETUP_PUTSALES:
            	putPromoterSales();
                break;
            case SETUP_PUTTASK:
            	putPromoterTask();
            	break;
            case SETUP_FINISHSYNC:
            	putSyncFinish();
            	break;
    	}
    }

    /**
     * 请求同步开始
     */
    private void requstStartSync(){
    	mHandler.sendEmptyMessage(SyncView.SYNC_1);
    	mConnectStep = SETUP_STARTSYNC;
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	mStartResult = ParseNetworkData.parseStartSyncResult(result);
            	if(mStartResult != null && mStartResult.Status == SyncModel.SUCCEED){
            		retryCount = 0;
            		requstModels();
            	}else{
            	    doRequestError(mStartResult);
            	}
            }
         }
        ).callPost(HttpUtil.getSyncStartUrl(), HttpUtil.getPutSyncstartContent(DataUtils.mUserData.mUuid, isFirstSync));
    }

    /**
     * 请求型号列表数据
     */
    private void requstModels(){
    	mConnectStep = SETUP_GETMODELS;
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	mProductResult = ParseNetworkData.parseModelsResult(result);
            	if(mProductResult != null && mStartResult.Status == SyncModel.SUCCEED){
            		retryCount = 0;
            		mHandler.sendEmptyMessage(SyncView.SYNC_2);
            		requstProjects();
            	}else{
            	    doRequestError(mProductResult);
            	}
            }
         }
        ).callPost(HttpUtil.getModelsUrl(), HttpUtil.getPutModelsContent(DataUtils.mUserData.mUuid));
    }

    /**
     * 请求数据标签项目数据
     */
    private void requstProjects(){
        mConnectStep = SETUP_GETPROJECTS;
        new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
                mProjectResult = ParseNetworkData.parseProjectResult(result);
                if(mProjectResult != null && mProjectResult.Status == SyncModel.SUCCEED){
                    retryCount = 0;
                    mHandler.sendEmptyMessage(SyncView.SYNC_3);
                    requstReminds();
                }else{
                    doRequestError(mProjectResult);
                }
            }
         }
        ).callPost(HttpUtil.getProjectLabelUrl(), HttpUtil.getPutProjectsContent(DataUtils.mUserData.mUuid));
    }

    /**
     * 请求提醒数据
     */
    private void requstReminds(){
        mConnectStep = SETUP_GETREMINDS;
        new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
                mReminderResult = ParseNetworkData.parseRemindResult(result);
                if(mReminderResult != null && mReminderResult.Status == SyncModel.SUCCEED){
                    retryCount = 0;
                    mHandler.sendEmptyMessage(SyncView.SYNC_4);
                    putPromoterCheckInfo();
                }else{
                    doRequestError(mReminderResult);
                }
            }
         }
        ).callPost(HttpUtil.getRemindUrl(), HttpUtil.getPutRemindsContent(DataUtils.mUserData.mUuid));
    }

    /**
     * 上传促销员签入信息数据
     */
    private void putPromoterCheckInfo(){
    	mConnectStep = SETUP_PUTCHECKINFO;
    	String putContent = HttpUtil.getPutPromoterCheckContent(mContext, DataUtils.mUserData.mUuid);
    	if(putContent == null){
    		mHandler.sendEmptyMessage(SyncView.SYNC_5);
    		putPromoterSales();
    		return;
    	}
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	final SyncModel.ResultStatus parseresult = ParseNetworkData.parsePromoterCheckResult(result);
            	if(parseresult != null && (parseresult.Status == SyncModel.SUCCEED || parseresult.Status == SyncModel.SUCCEED_PUTTED)){
            		Log.d("putPromoterCheckInfo=" + parseresult.Msg);
            		showErrorMsg(parseresult.Status, parseresult.Msg);
            		retryCount = 0;
            		mHandler.sendEmptyMessage(SyncView.SYNC_5);
            		putPromoterSales();
            	}else{
            	    doRequestError(parseresult);
            	}
            }
         }
        ).callPost(HttpUtil.getPromoterCheckUrl(), putContent);
    }

    /**
     * 上传促销员保存本地的销量信息数据
     */
    private void putPromoterSales(){
    	mConnectStep = SETUP_PUTSALES;
    	String putContent = HttpUtil.getPutPromoterSalesContent(mContext, DataUtils.mUserData.mUuid, SalesData.getInstance(mContext).getSavedModelList());
    	if(putContent == null){
    		mHandler.sendEmptyMessage(SyncView.SYNC_6);
    		putPromoterTask();
    		return;
    	}
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
                mPromoterSalesResult = ParseNetworkData.parsePromoterSalesResult(result);
            	if(mPromoterSalesResult != null && (mPromoterSalesResult.Status == SyncModel.SUCCEED || mPromoterSalesResult.Status == SyncModel.SUCCEED_PUTTED)){
            		retryCount = 0;
            		mHandler.sendEmptyMessage(SyncView.SYNC_6);
            		putPromoterTask();
            	}else{
            	    doRequestError(mPromoterSalesResult);
            	}
            }
         }
        ).callPost(HttpUtil.getPromoterSalesUrl(), putContent);
    }

    /**
     * 上传促销员特殊任务数据
     */
    private void putPromoterTask(){
    	mConnectStep = SETUP_PUTTASK;
    	String putContent = HttpUtil.getPutPromoterTasksContent(mContext, DataUtils.mUserData.mUuid);
    	if(putContent == null){
    		putSyncFinish();
    		return;
    	}
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	final SyncModel.ResultStatus parseresult = ParseNetworkData.parseResultStatus(result);
            	if(parseresult != null && (parseresult.Status == SyncModel.SUCCEED || parseresult.Status == SyncModel.SUCCEED_PUTTED)){
            		showErrorMsg(parseresult.Status, parseresult.Msg);
            		retryCount = 0;
            		putSyncFinish();
            	}else{
            	    doRequestError(parseresult);
            	}
            }
         }
        ).callPost(HttpUtil.getPromoterTaskUrl(), putContent);
    }

    /**
     * 同步完成
     */
    private void putSyncFinish(){
    	mConnectStep = SETUP_FINISHSYNC;
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	SyncModel.ResultStatus parseresult = ParseNetworkData.parseFinishSyncResult(result);
            	if(parseresult != null && parseresult.Status == SyncModel.SUCCEED){
            		retryCount = 0;
            		syncSuccessEnd();
            	}else{
            	    doRequestError(parseresult);
            	}
            }
         }
        ).callPost(HttpUtil.getFinishSyncUrl(), HttpUtil.getPutFinishSyncContent(DataUtils.mUserData.mUuid, mStartResult.SyncTime, SyncModel.TYPE_SYNC_ALL));
    }

    /**
     * 同步失败
     * @param status 状态
     * @param msg 失败消息
     */
    private void syncFail(int status, String msg){
        Log.e("syncFail="+mConnectStep);
    	if(retryCount < 3){
    		retryCount++;
    		retryConnect();
    	}else{
    		retryCount = 0;
    		mConnectStep = -1;
    		mHandler.sendEmptyMessage(SyncView.SYNC_FAILEDEND);
    		showErrorMsg(status, msg);
    	}
    }

    /**
     * 同步完成
     */
    private void syncSuccessEnd(){
        deletePutedData();
    	saveSyncData();
    	mConnectStep = -1;
    	retryCount = 0;
    	mHandler.sendEmptyMessage(SyncView.SYNC_SUCCESSEND);
    	Log.e("syncSuccessEnd");
    }

    /**
     * 删除已上传数据
     */
    private void deletePutedData(){
    	//SalesData.getInstance(mContext).clearAllData();
    	//mContext.getContentResolver().delete(StoresManagerSettings.SignInInfoColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
    	mContext.getContentResolver().delete(StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
    }

    /**
     * 保存同步成功之后的数据
     */
    private void saveSyncData(){
    	SyncUtil.saveModelList(mContext, mProductResult, isFirstSync);
    	SyncUtil.saveProjectsList(mContext, mProjectResult, isFirstSync);
    	SyncUtil.saveRemindList(mContext, mReminderResult, isFirstSync);
    	if(mPromoterSalesResult != null){
    	    DatabaseUtil.saveReportSalesData(mContext, SalesData.getInstance(mContext).getSavedModelList(), mPromoterSalesResult.SaleDate.getTime()); //将销量数据保存数据至本地
    	}
    }

	/**
	 * 重置数据
	 */
	private void resetData(){
		mStartResult = null;
		mProductResult = null;
		mPromoterSalesResult = null;
	}
	
	/**
	 * 数据清理
	 */
	public void detory(){
		
	}

	/**
	 * 检测是否第一次同步
	 */
	private boolean isFirstSync(){
		boolean isFirst = true;
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION,
				SyncUtil.PROJECTION, null, null, null); //查询
		if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()){ //数据存在 则表示非第一次同步
			isFirst = false;
		}
		if(cursor != null){
			cursor.close();
			cursor = null;
		}
		return isFirst;
	}

	/**
	 * 处理请求错误消息
	 */
	private void doRequestError(ResultStatus resultStatus){
	    String msg = null;
        int statusfail = 0;
        if(resultStatus == null){ //网络出现错误
            statusfail = SyncModel.FAIL_NETWORK; 
            msg = mContext.getString(R.string.network_fail);
        }else{ //数据出错
            statusfail = resultStatus.Status;
            msg = resultStatus.Msg;
        }
        syncFail(statusfail, msg);
	}

	/**
	 * 显示错误信息
	 * @param status 状态
	 * @param msg 错误消息
	 */
	private void showErrorMsg(int status, final String msg){
	    if(status == SyncModel.FAIL_DATA
	            || status == SyncModel.SUCCEED_PUTTED
	            || status == SyncModel.FAIL_DATA){
	        mHandler.post(new Runnable() {
	            @Override
	            public void run() {
	                // TODO Auto-generated method stub
	                Actions.toastShort(mContext, msg);
	            }
	        });
	    }
	}
}
